package com.partners.handler;

import com.partners.component.builder.TextBuilder;
import com.partners.configure.wechatmp.WxMpProperties;
import com.partners.dao.basic.CustomerDao;
import com.partners.dao.basic.FansDao;
import com.partners.dao.basic.UserDao;
import com.partners.dao.bo.FansDO;
import com.partners.dao.dto.NewsInputDTO;
import com.partners.dao.dto.TemplateDTO;
import com.partners.service.FansService;
import com.partners.service.TemplateService;
import com.partners.utils.TimestampUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
@Slf4j
public class SubscribeHandler extends AbstractHandler {

    @Resource
    private FansService fansService;

    @Resource
    private WxMpProperties wxMpProperties;

    @Resource
    private TemplateService templateService;

    @Resource
    private UserDao userDao;

    @Resource
    private CustomerDao customerDao;


    @Resource
    private FansDao fansDao;


    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) throws WxErrorException {
        this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());
        // 获取微信用户基本信息
        try {
            WxMpUser userWxInfo = weixinService.getUserService()
                .userInfo(wxMessage.getFromUser(), null);
            this.logger.info("注用户: " + userWxInfo);
            if (userWxInfo != null) {
                // TODO 可以添加关注用户到本地数据库
                this.logger.info("用户信息{}",wxMessage.getFromUser());
                String openId = userWxInfo.getOpenId();
                //查询是否存在记录
                Integer fanId =  fansService.getFansByOpenId(openId);
                FansDO fans = new FansDO();
                Integer addtime = TimestampUtils.timestamp();
                byte follow = 1;
                byte type = 1;
                if(fanId == null){
                    //新增用户
                  fans.setOpenid(userWxInfo.getOpenId());
                  fans.setAvatar(userWxInfo.getHeadImgUrl());
                  fans.setFollow(follow);
                  fans.setType(type);
                  fans.setSex(userWxInfo.getSex().byteValue());
                  fans.setNickname(userWxInfo.getNickname());
                  fans.setProvince(userWxInfo.getProvince());
                  fans.setCity(userWxInfo.getCity());
                  fans.setFollowtime(userWxInfo.getSubscribeTime().intValue());
                  fans.setAddtime(addtime);
                  Integer fansId = fansService.InsertFans(fans);

                  //查询该用户是否是扫码绑定
                  Integer id = userDao.getUserByOpenId(userWxInfo.getOpenId());
                  if(id != null){
                      //发送模板消息
                      String url = wxMpProperties.getBaseUrl()+"/loginPage/index?bind="+id;
                      String picUrl = "http://pmucjapyq.bkt.clouddn.com/6b43f157631cc0f73b30e111508e012.png";
                      NewsInputDTO newsInputDTO = new NewsInputDTO();
                      newsInputDTO.setUrl(url);
                      newsInputDTO.setPicUrl(picUrl);
                      newsInputDTO.setDescription("点击查看详情，进行用户身份绑定！");
                      newsInputDTO.setTitle("用户登录");
                      templateService.sendNewsMessage(newsInputDTO,userWxInfo.getOpenId());
                  }
                  //查询该客户是否是扫码绑定
                  Integer customer = customerDao.getCustomerDetailByOpenId(userWxInfo.getOpenId());
                  log.info("customer:{}",customer);
                  if(customer != null){
                      //发送图文消息领取优惠券
                      String url = wxMpProperties.getBaseUrl()+"/customerPage/scan_code?customer_id="+customer;
                      String picUrl = "http://pmucjapyq.bkt.clouddn.com/coupon.png";
                      NewsInputDTO newsInputDTO = new NewsInputDTO();
                      newsInputDTO.setUrl(url);
                      newsInputDTO.setPicUrl(picUrl);
                      newsInputDTO.setDescription("点击查收");
                      newsInputDTO.setTitle("恭喜你获取一张优惠券");
                      templateService.sendNewsMessage(newsInputDTO,userWxInfo.getOpenId());

                      //更新粉丝信息
                      FansDO fansDO = new FansDO();
                      fansDO.setFanid(fansId);
                      fansDO.setCustomerId(customer);
                      fansDao.updateByPrimaryKeySelective(fansDO);

                  }
                }else{
                   fans.setFanid(fanId);
                   fans.setFollow(follow);
                   fansService.UpdateFans(fans);
                }
            }
        } catch (WxErrorException e) {
                this.logger.info("报错信息{}",e.getError().getErrorMsg());
            if (e.getError().getErrorCode() == 48001) {
                this.logger.info("该公众号没有获取用户信息权限！");
            }
        }


        WxMpXmlOutMessage responseResult = null;
        try {
            responseResult = this.handleSpecial(wxMessage);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        if (responseResult != null) {
            return responseResult;
        }

        try {
            return new TextBuilder().build("感谢关注", wxMessage, weixinService);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        return null;
    }

    /**
     * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
     */
    private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage)throws Exception {
        String sceneStr = null;
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        sceneStr = wxMessage.getEventKey().toString();
        this.logger.error("sceneStr:{}",sceneStr);
        String redirectUrl = "http://lyl.natapp1.cc/customer/customerList/1";
        response.sendRedirect(redirectUrl);
//        if(sceneStr != null){
//            String scene = sceneStr.substring(8);
//            fansService.getSceneStr(scene);
//        }
//
        return null;
    }

}
